//
//  Engineer_adjustVC.swift
//  EngineerModel
//
//  Created by SSLong on 2018/4/18.
//  Copyright © 2018年 孙世龙. All rights reserved.
//

import UIKit

let kBeacon_Recive_Time = 20

class Engineer_adjustVC: UIViewController {
    
    var adjustModel: HD_Beacon_Obj?
    //属性
    var calculateTime : Int?       //统计次数
    var totalTime    : Int?       //总次数
    var disArray     :Array<String>? //统计距离数组
    var accStr       :String?     //距离
    var rssiStr      :String?     //rssi
    var nowBeaconNum :Int?        //当前号
    var isShowAlert  :Bool = false//
    var mediator = HD_NKM_Mediator.shareInstance() as! HD_NKM_Mediator
    
    @IBOutlet weak var progressL       : UILabel!        //收号进度
    @IBOutlet weak var setAccurictyL   : UITextField!    //设置距离
    @IBOutlet weak var iBeaconNumL     : UILabel!        //当前号
    @IBOutlet weak var progressV       : UIProgressView! //收号进度
    @IBOutlet weak var newAccurictyL   : UILabel!        //计算后得到新的距离
    @IBOutlet weak var allIBeaconsInfoL: UITextView!     //所有收号信息
    @IBOutlet weak var startBtn        : UIButton!       //开启收号按钮
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //接收通知
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(beaconNoti),
                                               name: NSNotification.Name(rawValue: iBeacon_Send_Notification),
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(ALLbeaconNoti),
                                               name: NSNotification.Name(rawValue: All_iBeacon_Send_Notification),
                                               object: nil)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        judgeIsModelValide()
        //开启收号
        mediator.startRangingAllRegions()
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        //关闭收号
        mediator.stopRangingAllRegions()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "校准页面"
        
        initDatas()
    }
    func judgeIsModelValide() {
        //判断卡号是否有效
        if adjustModel==nil || adjustModel?.major == nil || adjustModel?.minor == nil {
            weak var weakSelf = self
            let alert = UIAlertController.init(title: "提示", message: "当前参数错误，请返回", preferredStyle: UIAlertControllerStyle.alert)
            let okAction = UIAlertAction.init(title: "返回", style: UIAlertActionStyle.default, handler: { (alert) in
                //切换楼层地图
                weakSelf?.backAction()
            })

            alert.addAction(okAction)
            
            self.navigationController?.present(alert, animated: true, completion: nil)
        }
    }
    func backAction() -> Void {
        self.navigationController?.popViewController(animated: true)
    }
    func initDatas() {
        //
        accStr = "0"
        calculateTime = 0
        totalTime = kBeacon_Recive_Time
        disArray = Array.init()

        
        self.setAccurictyL.text = String.init(format: "%.2lf", (self.adjustModel?.accIos)!)
        iBeaconNumL.text = String.init(format: "major:%@ minor:%@", ((self.adjustModel?.major ?? 0).stringValue), ((self.adjustModel?.minor ?? 0).stringValue))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func action_startGetiBeacons(_ sender: UIButton) {
        startBtn.isSelected = !startBtn.isSelected
    }
    
    // MARK: - 2、保存数据库，更新设置卡号
    @IBAction func action_saveBack(_ sender: UIButton) {
        //1、保存数据库
        
        //2、返回
        backAction()
    }
    
    
    
}
//MARK:------收号处理----------------
extension Engineer_adjustVC {
    //MARK:---------蓝牙收号处理
    //收号，本层放大，其他楼层弹出提示
    @objc func beaconNoti(notification: NSNotification) {
        
        let beacon: HD_Beacon_Obj = notification.object as! HD_Beacon_Obj
        
        print("当前收号是\(beacon.major)")
        nowBeaconNum = beacon.minor as? Int;
        
        
    }
    //MARK: -----显示调试信息-----
    @objc func ALLbeaconNoti(notification: NSNotification) {
        let beaconA = notification.object as! [CLBeacon]
        
        if beaconA.count == 0 {
            return
        }
        
        updateLabelAction(allBeaconArray: beaconA)

        //
        if  startBtn.isSelected{
            //
            calculateSelectNum(allBeaconArray: beaconA)
        }
    }
    func calculateSelectNum(allBeaconArray: Array<CLBeacon>) -> Void {
        //1、设置卡，号必须是唯一的（不能有两张卡是同一个号）
        let array = allBeaconArray.filter { (bea: CLBeacon) -> Bool in
            
            return bea.minor == adjustModel?.minor
        }
        if array.count > 1 && isShowAlert == false{
            weak var weakSelf = self
            let alert = UIAlertController.init(title: "提示", message: "存在多个minor相同的卡号，请返回。", preferredStyle: UIAlertControllerStyle.alert)

            let okAction = UIAlertAction.init(title: "返回", style: UIAlertActionStyle.default, handler: { (alert) in
                weakSelf?.isShowAlert = false
                weakSelf?.backAction()
            })
            
            alert.addAction(okAction)
            
            self.navigationController?.present(alert, animated: true, completion: nil)
            isShowAlert = true
        }
        //2、只有一个信号是我们要设置的卡
        if array.count == 1 {
            if calculateTime! < totalTime! {
                let bea = array[0]
                let disStr = String.init(format: "%f", bea.accuracy)
                disArray?.append(disStr)
                calculateTime! = calculateTime! + 1
                
            }else{
                caculateDisAction(arr: disArray!)
            }
        }
        //3、显示
        DispatchQueue.main.async {
            self.progressL.text = String.init(format: "收号进度：(%d/%d)", self.calculateTime!,self.totalTime!)
            let pro : Float = Float(self.calculateTime!) / Float(self.totalTime!)
            self.progressV.setProgress(pro, animated: true)
        }
        
    }

    func caculateDisAction(arr: Array<String>) -> Void {
        //
        var averageDis : Double = 0.0
        
        let sortArray = arr.sorted { (obj1: String, obj2: String) -> Bool in
            return Double(obj1)! > Double(obj2)!
        }
        print(sortArray)
        for str in 1 ..< sortArray.count - 1 {
            
            averageDis = averageDis + Double(sortArray[str])!
            
        }
//        print(averageDis)
        
        averageDis = averageDis / Double(sortArray.count - 2)
        
        newAccurictyL.text = String.init(format: "%f", averageDis)
        setAccurictyL.text = String.init(format: "%f", averageDis)
        
    }
    
    func updateLabelAction(allBeaconArray: Array<CLBeacon>) -> Void {
        //
        let singleMinor: String = String.init(format: "当前单点号:%d, 距离阈值:%@\n", nowBeaconNum ?? 0,mediator.nowThre())
        var beaconsInfo :String = ""
        beaconsInfo.append(singleMinor)
        beaconsInfo.append("周边蓝牙信息:\n")
        
        for bea in allBeaconArray {
            let mess = String.init(format: "Minor:%d -- Rssi:%d Acc:%.2f\n", bea.major.intValue,bea.rssi,bea.accuracy)
            beaconsInfo.append(mess)
        }
        
        allIBeaconsInfoL.text = beaconsInfo
    }
}
